import React, { forwardRef, useContext, useEffect, useImperativeHandle, useRef, useState } from 'react';
import CustomPopover from './CustomPopover';
import './custom-popover.scss';
import { Button, Empty, Space, Tag, Tooltip, Upload, UploadProps } from 'antd';
import { BookOutlined, CloudUploadOutlined, PaperClipOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import * as XLSX from "xlsx";
import { handleDownloadByName, handleDownloadByNameV2, toastShort } from '../../utils';
import systemApi from '../../api/system';
import { DocConfig, SpeciesInfoType } from '../../utils/types';
import LoadingWapper from '../loading/LoadingWapper';
import comDocContext from './../../context/DocContext';
import { fillSpeciesNameInfoForSlateEditor } from '../../views/office-lib/word-editor/utils';
import { DocItem } from '../../views/slate-editor';

interface Props {
    clientX: number
    clientY: number
    fillSpeciesInfoList: Function
}

const CanoricalMePopover = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        openPopover
    }))

    const {
        comDocInstance,
        _setComDocInstance,
        comDocConfig,
        _setComDocConfig,
        comFocusTopicNode,
    } = useContext(comDocContext);

    useEffect(() => {
        console.log("comDocConfig--->", comDocConfig);
        if (
            comDocConfig &&
            comDocConfig.docExtraConfigInfo &&
            comDocConfig.docExtraConfigInfo.speciesInfoList
        ) {
            setSpeciesInfoList(comDocConfig.docExtraConfigInfo.speciesInfoList)
        }
    }, [comDocConfig])

    const {
        clientX,
        clientY,
        fillSpeciesInfoList
    } = props;

    const delayTimer = useRef<any>(null);
    const delayTimer2 = useRef<any>(null);
    const [percent, setPercent] = useState<number>(0);
    const currentPercent = useRef<number>(0);
    const isActive = useRef<boolean>(false);
    const customSelectRef = useRef<any>(null);
    const tempDownloadUrl = useRef<string>(null);

    const [loading, setLoading] = useState(false);
    const [speciesInfoList, setSpeciesInfoList] = useState<SpeciesInfoType[]>([]);

    useEffect(() => {
        return () => {
            delayTimer.current && clearTimeout(delayTimer.current);
            delayTimer2.current && clearTimeout(delayTimer2.current);
        }
    }, [])

    const openPopover = () => {
        customSelectRef.current.show();
    };

    const uploadProps: UploadProps = {
        name: 'file',
        showUploadList: false,
        beforeUpload: (file) => {
            console.log("beforeUpload---->", file)
            let reader = new FileReader()
            reader.readAsBinaryString(file)//读取这个文件
            let _uploadParamsList = [];
            reader.onload = function (event) {
                try {
                    let result = event.target.result
                    let xlsxdata = XLSX.read(result, { type: 'binary' })//读取xlsx
                    // console.log("xlsxdata.Sheets--->", xlsxdata.Sheets)
                    const workSheetNameList: string[] = xlsxdata.SheetNames;
                    // console.log("workSheetNameList--->", workSheetNameList)
                    const spaciesSheet: string[][] = XLSX.utils.sheet_to_json(xlsxdata.Sheets[workSheetNameList[0]], { header: 1, defval: '', blankrows: true });
                    // console.log("spaciesSheet----->", spaciesSheet)
                    const tempSpeciesNameList = [];
                    spaciesSheet.forEach((row, rowIndex) => {
                        if (rowIndex > 0 && row[0]) {
                            tempSpeciesNameList.push(row[0])
                        }
                    })
                    setLoading(true);
                    let params = {
                        names: tempSpeciesNameList
                    };
                    systemApi.querySpeciesInfoMutiple(params)
                        .then(res => {
                            setLoading(false);
                            console.log("querySpeciesInfoMutiple--->", res)
                            let tempspeciesInfoList = [];
                            tempSpeciesNameList.forEach(speciesName => {
                                const find = res.data.list.find(ele => {
                                    return ele.species_c === speciesName;
                                })
                                if (find) {
                                    tempspeciesInfoList.push(find)
                                } else {
                                    tempspeciesInfoList.push({
                                        species_c: speciesName
                                    })
                                }
                            })
                            setSpeciesInfoList(tempspeciesInfoList);
                            let _tempComDocConfig = comDocConfig;
                            _tempComDocConfig.docExtraConfigInfo.speciesInfoList = tempspeciesInfoList;
                            handleUpdateComDocConfig(_tempComDocConfig);
                        })
                        .catch(err => {
                            setLoading(false);
                        })
                } catch (e) {

                }
            }
            return false;
        },
        onChange(info) {
            return false;
        },
    };

    const handleUpdateComDocConfig = (newDocConfig: DocConfig) => {
        let filterDoConfig = { ...newDocConfig };
        delete filterDoConfig.docExtraConfigInfo.dataVerificationMap;
        delete filterDoConfig.docExtraConfigInfo.mergeBoundInfo;
        filterDoConfig.updateComponentName = 'EditPageNav';
        _setComDocConfig(filterDoConfig);
    }

    const handleStartInsert = () => {
        if (speciesInfoList.length == 0) {
            return toastShort("error", "请上传物种清单")
        }
        let realUseSpeciesInfoList = speciesInfoList.filter(ele => {
            return ele.canorical_me;
        })
        const docItemList:DocItem[] = [
            {
                "id": "64accf3d4a7e99a264c10577-p",
                //@ts-ignore
                "type": "p",
                "text": "测试样式工具保护地范围的确定以能够有效保护构成地质公园的主要地质遗迹、主要地质景观为首要原则，与相关保护规划相协调的原则，并充分考虑地质公园保护及管理与周边居民点（村庄）活动相适应等因素，合理划定地质公园规划面积。主要保护对象为世界珍禽梅花鹿以及以云杉、豹猫、华北落叶松为主的天然次生林生态系统。",
                "data": null,
                "plainText": "测试样式工具保护地范围的确定以能够有效保护构成地质公园的主要地质遗迹、主要地质景观为首要原则，与相关保护规划相协调的原则，并充分考虑地质公园保护及管理与周边居民点（村庄）活动相适应等因素，合理划定地质公园规划面积。主要保护对象为世界珍禽梅花鹿以及以云杉、豹猫、华北落叶松为主的天然次生林生态系统。"
            },
            {
                "id": "64accf3c4a7e99a264c10553-p",
                //@ts-ignore
                "type": "p",
                "text": "测试样式工具$$[0] 111，狼 222",
                "data": null,
                "style": {},
                "plainText": "测试样式工具豹猫 111，狼 222",
                "textStyleMap": {
                    "$$[0]": {
                        "text": "豹猫",
                        "bold": true
                    }
                }
            }
        ]
        // fillSpeciesNameInfoForSlateEditor(
        //     docItemList,
        //     realUseSpeciesInfoList
        // )
        fillSpeciesInfoList && fillSpeciesInfoList(realUseSpeciesInfoList);
        customSelectRef.current._handleClose();
    }

    const handleDownLoadTemplate = () => {
        handleDownloadByNameV2(
            'http://shpfile-data-1314977817.cos.ap-guangzhou.myqcloud.com/public/20230824512668dc1a-5e2b-43d9-ae46-72343666d02e67.xlsx',
            '物种名单上传模版'
        )
    }

    return (
        <CustomPopover
            ref={customSelectRef}
            clientX={clientX}
            clientY={clientY}
            contentRender={(props) => (
                <div className='flex-col canorical-me-popover'>
                    <div className='flex-row canorical-me-popover-content'>
                        <LoadingWapper
                            loading={loading}
                        />
                        {
                            speciesInfoList.length ?
                                <>
                                    {
                                        speciesInfoList.map((speciesInfo, index) => {
                                            return (
                                                <div
                                                    key={index + ''}
                                                    className='species-name-tag'
                                                >
                                                    {
                                                        speciesInfo.canorical_me ?
                                                            <Tag
                                                                color="blue"
                                                                className='flex-row'
                                                                title={`${speciesInfo.species_c}(${speciesInfo.canorical_me})`}
                                                            >
                                                                {speciesInfo.species_c}
                                                                {
                                                                    <div
                                                                        style={{ fontStyle: 'italic', maxWidth: 72 }}
                                                                        className='single-line-text'
                                                                    >({speciesInfo.canorical_me})</div>
                                                                }
                                                            </Tag>
                                                            :
                                                            <Tag
                                                                color="red"
                                                                className='flex-row'
                                                            >
                                                                {speciesInfo.species_c}(查询失败)&nbsp;
                                                                <Tooltip title={'在本系统物种库中，未能查询到此物种信息'}>
                                                                    <QuestionCircleOutlined />
                                                                </Tooltip>
                                                            </Tag>
                                                    }
                                                </div>
                                            )
                                        })
                                    }
                                </>
                                :
                                <div className='canorical-me-popover-empty'>
                                    <Empty
                                        description={"暂无物种名单"}
                                    />
                                </div>
                        }
                    </div>
                    <div className='flex-row canorical-me-popover-footer'>
                        <Upload {...uploadProps}>
                            <Button
                                icon={<CloudUploadOutlined />}
                            >
                                上传物种名单
                            </Button>
                        </Upload>
                        <Button
                            type={'primary'}
                            icon={<BookOutlined />}
                            loading={loading}
                            style={{ marginLeft: 12 }}
                            onClick={handleStartInsert}
                        >
                            填充拉丁名
                        </Button>
                    </div>
                    <div
                        className='link-text'
                        style={{ marginBottom: 12 }}
                        onClick={handleDownLoadTemplate}
                    >
                        <PaperClipOutlined />
                        物种名单上传模版.xlsx
                    </div>
                </div>
            )}
        />
    )
}


export default forwardRef(CanoricalMePopover);